
#ifndef __WEBSERVER__
#define __WEBSERVER__

#include <iostream>
#include "TcpSocket.hpp"
#include  <unistd.h>
#include <thread>
#include <signal.h>
#include <functional>
#include "Entrance.hpp"
#include "ThreadPool.hpp"
#include <sys/socket.h>

typedef std::function<void*(const int)> function;

#define  QUEUE_TASK_NUM 3     // 任务队列最大数

//制作一个初始化服务端的类型——使用单例模式

template <class T>
class webserver
{
typedef ThreadPool<T*> thread_pool;

private:
    int _port = -3;
    int _server_socket = -3;
    thread_pool* st = nullptr;

public:
    webserver()
    {
        signal(SIGPIPE, SIG_IGN);
        // 防止send，向关闭管道写入，导致webserver崩溃
    }
    
    void initial(int _port, thread_pool* th_pool)
    {
        MySocket tool;
        _server_socket = tool._socket_set();
        // 设置复用端口号
        int tmp = 1;
        if (setsockopt(_server_socket, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp)) < 0)
            std::cout << "setsockopt fail" << std::endl;

        tool.bind_set(_server_socket,_port);
        Logmessage(INFO, "服务端初始化成功");

        //启用线程池
        st = th_pool; 
    }

    void work_begin()
    {
        MySocket tool;
        tool.listen_run(_server_socket);
        while (1)
        {
            sockaddr_in cline;
            uint16_t cline_prot;
            int actual_socket = tool.accept_run(_server_socket, &cline, &cline_prot);
            if (actual_socket != -1)
            {
                Logmessage(INFO, "connect success 标识符:%d", actual_socket);
            }
            
            //接收到请求后，想任务池中添加任务---线程池方案
             if (st->Get_queue_task_reserver_size() < QUEUE_TASK_NUM)
            {
                  Thread_Task* task = new Thread_Task(actual_socket);
                  st->push(task);
                  st->swap_queue(QUEUE_TASK_NUM);
            }
         }
    }

};


#endif





